const { Service } = require("egg");

const nodemailer = require("nodemailer");
const fse = require("fs-extra");
const path = require("path");  
// 你的邮箱用户名
const userEmail = "---------.com";

const transporter = nodemailer.createTransport({
      host: "smtp.126.com",
      port: 25,
      auth: {
            user: userEmail,
            pass: "XXXXXXXXX", // 如果你是网易邮箱，这个pass就可能是授权密码
      },
});

class ToolService extends Service {
      async sendMail(email, subject, text, html) {
            try {
                  await transporter.sendMail({
                        from: userEmail,
                        cc: userEmail,
                        to: email,
                        subject,
                        text,
                        html,
                  });

                  return { success: true, message: "发送成功" };
            } catch (e) {
                  return { success: false, message: e };
            }
      }

      async mergeFile(filePath, fileHash, size) {
            const chunkDir = path.resolve(this.config.UPLOAD_DIR, fileHash);
            let chunks = await fse.readdir(chunkDir);
            chunks.sort((a, b) => a.split("-")[1] - b.split("-")[1]);
            chunks = chunks.map((cp) => path.resolve(chunkDir, cp));
            await this.mergeChunks(chunks, filePath, size, fileHash);
      }

      async mergeChunks(files, dest, size, fileHash) {
            const pipStream = (filePath, writeStream) =>
                  new Promise((resolve) => {
                        const readStream = fse.createReadStream(filePath);
                        readStream.on("end", () => {
                              resolve();
                        });

                        readStream.pipe(writeStream);
                  });
            // The value of "start" is out of range. It must be an integer. Received 104857.6
            // fs-extra中的createWriteStream，start参数值不能为小数，所以注意下size
            await Promise.all(
                  files.map((file, index) => {
                        pipStream(
                              file,
                              fse.createWriteStream(dest, {
                                    start: index * size,
                                    end: (index + 1) * size,
                              })
                        );
                  })
            );

            const fileDirPath = path.resolve(this.config.UPLOAD_DIR, fileHash);
            fse.remove(fileDirPath);
      }
 
}

module.exports = ToolService;
